// utils/request.js
import axios from 'axios'
import axiosAdapterUniapp from 'axios-adapter-uniapp'
import {
	ref
} from 'vue'

const api = "http://localhost:8080"

// 创建axios实例
const service = axios.create({
	baseURL: api,
	adapter: axiosAdapterUniapp,
	timeout: 15000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		const token = '';

		// 如果token存在，添加到请求头
		if (token) {
			config.headers['Authorization'] = `Bearer ${token}`
		}

		// 微信小程序端添加特定header
		// #ifdef MP-WEIXIN
		config.headers['X-Requested-With'] = 'XMLHttpRequest'
		config.headers['Content-Type'] = 'application/json'
		// #endif

		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use(
	(response) => {
		const res = response.data

		// 这里根据你的后端返回结构进行调整
		if (res.code === 401) {
			return Promise.reject(new Error(res.message || 'Error'))
		} else if (res.code === 500) {
			return Promise.reject(new Error(res.message || 'Error'))
		} else {
			return res.data
		}
	},
	(error) => {
		console.log('err' + error)
		return Promise.reject(error)
	}
)

/**
 * 封装get请求
 * @param {string} url 
 * @param {object} params 
 * @returns {Promise}
 */
export function get(url, params = {}) {
	return new Promise((resolve, reject) => {
		service.get(url, {
				params
			})
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}

/**
 * 封装post请求
 * @param {string} url 
 * @param {object} data 
 * @returns {Promise}
 */
export function post(url, data = {}) {
	return new Promise((resolve, reject) => {
		service.post(url, data)
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}

export default {
	get,
	post
}